package com.mazaiting.generator.service.impl;

import cn.hutool.core.io.IoUtil;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.exceptions.BusinessException;
import com.mazaiting.common.core.ex.exceptions.EmptyObjectException;
import com.mazaiting.generator.config.GeneratorProperties;
import com.mazaiting.generator.domain.entity.TemplateFileEntity;
import com.mazaiting.generator.domain.query.DownloadQuery;
import com.mazaiting.generator.domain.query.PreviewQuery;
import com.mazaiting.generator.service.IDatasourceService;
import com.mazaiting.generator.service.IGeneratorService;
import com.mazaiting.generator.service.ITableService;
import com.mazaiting.generator.service.ITemplateFileService;
import com.mazaiting.generator.utils.GenUtil;
import com.mazaiting.generator.utils.TemplateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 代码生成
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GeneratorServiceImpl implements IGeneratorService {

    private final ITableService tableService;
    private final IDatasourceService datasourceService;
    private final GeneratorProperties generatorProperties;
    private final ITemplateFileService templateFileService;

    @Override
    public void downloadCode(Long tableId, ZipOutputStream zos) throws BusinessException, IOException {
//        try {
//            PreviewQuery previewQuery = new PreviewQuery();
//            // 数据模型
//            Map<String, Object> dataModel = tableService.getDataModel(previewQuery);
//            // 模板名
//            String templateName = previewQuery.getFileType().getTemplateName();
//            // 设置模板名
//            dataModel.put("templateName", templateName);
//            // 生成内容
//            String content = TemplateUtil.getContent(WebUtil.getContent(generatorProperties.getTemplate() + "/" + templateName), dataModel);
//        } catch (Exception e) {
//            throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), "模板写入失败", e);
//        }

//        String tempPath = "src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java";
//        String path = TemplateUtil.getContent(tempPath, )
//        // 渲染模板并输出
//        for (TemplateInfo template : TEMPLATE_INFO_LIST) {
//            // 获取模板名
//            String templateName = template.getTemplateName();
//            dataModel.put("templateName", templateName);
//            String content = TemplateUtil.getContent(WebUtil.getContent(generatorProperties.getTemplate() + "/" + templateName), dataModel);
//            String path = TemplateUtil.getContent(template.getGeneratorPath(), dataModel);
//
//            try {
//                // 添加到zip
//                zos.putNextEntry(new ZipEntry(path));
//                IoUtil.writeUtf8(zos, false, content);
//                zos.flush();
//                zos.closeEntry();
//            } catch (IOException e) {
//                throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), "模板写入失败：" + path, e);
//            }
//        }
    }

    @Override
    public byte[] download(DownloadQuery downloadQuery, String dir) throws Exception {

        // 表名列表
        List<String> tableNameList = Arrays.stream(downloadQuery.getTableNames().split(",")).toList();

        // 根据组 ID 查询文件列表
        List<TemplateFileEntity> templateFileList = templateFileService.lambdaQuery().eq(TemplateFileEntity::getGroupId, downloadQuery.getTemplateGroupId()).list();
        if (CollectionUtils.isEmpty(templateFileList)) {
            throw new EmptyObjectException(ResultCode.COMMON_FAIL.getCode(), "模板文件列表为空");
        }
        // 构建预览对象
        PreviewQuery previewQuery = new PreviewQuery();
        previewQuery.setProjectId(downloadQuery.getProjectId());
        previewQuery.setDatasourceId(downloadQuery.getDatasourceId());

        try (
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                ZipOutputStream zos = new ZipOutputStream(outputStream)
        ) {

            // 遍历表名
            for (String tableName : tableNameList) {
                // 遍历生成文件
                for (TemplateFileEntity templateFile : templateFileList) {
                    // 设置表名
                    previewQuery.setTableName(tableName);
                    // 数据模型
                    Map<String, Object> dataModel = tableService.getDataModel(previewQuery);
                    // 路径
                    String filePath = templateFile.getFilePath();
                    // 文件名
                    String fileName = templateFile.getFileName();
                    // 模板名
                    String templateName = filePath + File.separator + fileName;
                    // 设置模板名
                    dataModel.put("templateName", templateName);

                    // 模板内容
                    String templateContent = GenUtil.getFileContent(generatorProperties, templateFile);;

                    // 生成内容
                    String content = TemplateUtil.getContent(templateContent, dataModel);
                    // java 生成后的文件名取类名
                    String tempPath = dir + File.separator + templateName.substring(0, templateName.length() - 4);
                    String path = TemplateUtil.getContent(tempPath, dataModel);

                    // 添加到zip
                    zos.putNextEntry(new ZipEntry(path));
                    IoUtil.writeUtf8(zos, false, content);
                    zos.flush();
                    zos.closeEntry();
                }
            }

            // 关闭流
            IoUtil.close(zos);
            // 调用前必须先关闭 zip 流
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new BusinessException(ResultCode.COMMON_FAIL.getCode(), "模板写入失败", e);
        }
    }

//
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void generatorCode(Long tableId) {
//        // 数据模型
//        Map<String, Object> dataModel = getDataModel(tableId);
//
//        // 代码生成器信息
//        GeneratorInfo generator = generatorConfig.getGeneratorConfig();
//
//        // 渲染模板并输出
//        for (TemplateInfo template : generator.getTemplates()) {
//            dataModel.put("templateName", template.getTemplateName());
//            String content = TemplateUtils.getContent(template.getTemplateContent(), dataModel);
//            String path = TemplateUtils.getContent(template.getGeneratorPath(), dataModel);
//
//            FileUtil.writeUtf8String(content, path);
//        }
//    }

}